package com.dorukdestan.p2pshare.util;

import java.io.File;
import java.util.Stack;

import com.dorukdestan.p2pshare.model.Constants;
import com.dorukdestan.p2pshare.model.SharedFile;
import com.dorukdestan.p2pshare.storage.SharedFoldersAndFiles;

public class FileOperations {
	
	private static Stack<File> directoryStack;
	
	public static boolean addDirectory(String path){
		directoryStack = new Stack<File>();
		hashAll(path);
		
		return SharedFoldersAndFiles.sharedFiles.size() > 0;
	}

	/**
	 * @return - a SharedFile object or null if file not null
	 */
	public static SharedFile searchByName(String fileName){
		
		for (String name : SharedFoldersAndFiles.sharedFilesByName.keySet()) {
			boolean found = fileName.equalsIgnoreCase(name);
			if(found){
				return SharedFoldersAndFiles.sharedFilesByName.get(name);
			}
		}
		return null;
	}
	
	/**
	 * @return - a SharedFile object or null if file not null
	 */
	public static SharedFile searchByHash(long fileHash){
		return SharedFoldersAndFiles.sharedFiles.get(fileHash);
	}
	
	/**
	 * Hashes and adds recursively all files to the program's data structure which represents shared files.
	 * @param path
	 */
	private static void hashAll(String path){
		
		if(path == null)
			return;
		
		File root = null;
		try {
			root = new File(path);
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		if(root.isDirectory()){
			
			File[] filesArray = root.listFiles(Constants.directoryFilter);
			
			//Add all directories to a stack
			for (File file : filesArray) {
				directoryStack.push(file);
			}
			
			//Add all files to sharedList
			filesArray = root.listFiles(Constants.fileFilter);
			
			for (File file : filesArray) {
				SharedFile sf = new SharedFile(file.getAbsolutePath());
				SharedFoldersAndFiles.sharedFiles.put(sf.getHashValue(), sf);
				SharedFoldersAndFiles.sharedFilesByName.put(sf.getName(), sf);
			}
		}
		
		//Make a recursive call
		if(!directoryStack.isEmpty()){
			hashAll(directoryStack.pop().getAbsolutePath());
		}
	}
	
//	public static void main(String[] args) {
//		
////		hashAll("/home/destan/Downloads");
////
////		for (SharedFile file: SharedFoldersAndFiles.sharedFiles.values()) {
////			
////			System.out.println(file.getName() + "\t\t\t\t\t\t" + file.getHashValue());
////		}
//		
//		File f1 = new File("/home/destan/Desktop/resources");
//		System.out.println(f1.lastModified());
//		
//
//		f1 = new File("/home/destan/Desktop/resources/i18n/i18n_tr.properties");
//		System.out.println(f1.lastModified());
//		
//		f1 = new File("/home/destan/Desktop/resources/asinus-beans-custom.xml");
//		System.out.println(f1.lastModified());
//		
//		
//	
//	}
	
}
